package com.xk.auth.service;

import com.hy.common.enums.ExceptionEnums;
import com.hy.common.exception.XkException;
import com.xk.auth.client.UserClient;
import com.xk.auth.config.JwtProperties;
import com.xk.auth.entiy.UserInfo;
import com.xk.auth.utils.JwtUtils;
import com.xk.user.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@EnableConfigurationProperties(JwtProperties.class)
public class AuthService {
    /**
     * 登录授权
     * @param username
     * @param password
     * @return
     */
    @Autowired
    private UserClient userClient;
    @Autowired
    private JwtProperties prop;

    public String login(String username, String password) {

        try {
            //校验用户名和密码，校验远程调用用户中心的服务
            User user = userClient.queryUserBynameAndPwd(username, password);
            if (user==null){
                throw new XkException(ExceptionEnums.INVALID_USERNAME_PASSWORD);
            }

            String token = JwtUtils.generateToken(new UserInfo(user.getId(), username),
                    prop.getPrivateKey(), prop.getExpire());
            return token;
        } catch (Exception e) {
            log.error("token凭证生成失败");
            throw new XkException(ExceptionEnums.CREATE_TOKEN_ERROR);


        }


    }
}
